/*
 * Copyright (c) 2007 The Trustees of Indiana University. All rights reserved.
 * IU CSCI B534 Distributed Systems 2007-02-01 http://www.cs.indiana.edu/classes/b534
 */

package edu.indiana.cs.b534.torrent.struct;

import edu.indiana.cs.b534.torrent.TInteger;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;

public class TIntegerImpl implements TInteger {

    protected Integer value;
    public static final boolean DEBUG = Boolean.parseBoolean(System.getProperty("debug"));

    public static TInteger deserialize(InputStream inStream) throws IOException {
        char ch = 0;
        StringBuffer strBuffer = new StringBuffer(); // dont expect length to be > 40 bytes
        ch = (char)inStream.read(); // read 'i'
        if (DEBUG) System.out.println("I> " + ((char)ch));
        if(ch != 'i') throw new IOException("Not a valid integer encoding. Does not start with char 'i'");

        ch = (char)inStream.read(); // read digit
        while(ch != 'e') {
            strBuffer.append(ch);
            ch = (char)inStream.read(); // read digit or 'e'
            if (DEBUG) System.out.println("I> " + ((char)ch));
        }
        if (DEBUG) System.out.println("I> " + ((char)ch));
        int intVal = Integer.parseInt(strBuffer.toString());
        if (DEBUG) System.out.println("IVALUE=" + intVal);

        // create and return an instance
        TIntegerImpl instance = new TIntegerImpl();
        instance.setValue(intVal);
        return instance;
    }

    public static TInteger newInstance() {
        return new TIntegerImpl();
    }
    
    public static TInteger newInstance(int value) {
        TIntegerImpl tint = new TIntegerImpl();
        tint.setValue(value);
        return tint;
    }

    public int getValue(){
        return value;
    }

    public void setValue(int value_){
        value = value_;
    }

    public int hashCode() { return value.hashCode(); }
    public boolean equals(Object obj){ return value.equals(obj); }
    public String toString() { return value.toString(); }
    public OutputStream serialize(OutputStream outStream) throws IOException {
        ByteBuffer valBuffer = CHARSET.encode(String.valueOf(getValue()));

        outStream.write('i'); // prefix
        outStream.write(valBuffer.array(), 0, valBuffer.limit()); // value
        outStream.write('e'); // suffix
        return outStream;
    }
}
